package com.moka.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseVersionManager extends SQLiteOpenHelper{

	
	public DatabaseVersionManager(Context context) {
		super(context, "dbVersion", null, 1);
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		
		String sql = "create table dbVersion (id integer primary key autoincrement, name varchar, versionNum integer)";
		
		db.execSQL(sql);
		
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		
	}
	
	public int getVersion(String databaseName){
		
		int version = 0;
		
		SQLiteDatabase db = getReadableDatabase();
		
		Cursor cursor = null;
		
		try{
		
			cursor = db.rawQuery("select versionNum from dbVersion where name = ?", new String[]{"db/"+databaseName});
				
			if(cursor.moveToFirst()){
			
				version = cursor.getInt(cursor.getColumnIndex("versionNum"));
			
			}
		
		}finally{
		
			if(cursor!=null){
				
				cursor.close();
				
			}
			
			db.close();
			
		}
		
		return version;
	}
	
	public void setVersion(String name,int version){
		
		SQLiteDatabase db = getWritableDatabase();
		
		try{
		
			db.delete("dbVersion", " name=? ", new String[]{name});
			
			ContentValues cv = new ContentValues();
			
			cv.put("name",name);
			
			cv.put("versionNum", version);
			
			db.insert("dbVersion", null, cv);
			
		}finally{
		
			db.close();
		
		}
		
	}

}
